package com.game.service.app;


import com.game.service.define.RoomConfig;
import com.game.service.socket.FileUtils;
import com.game.service.windows.LogWindows;
import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import static com.game.service.define.RoomConfig.LOG_NAME_ERROR;


public class Utils {
    public static String encryptMD5(String input) {
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(input.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式

    public static String getFormattedDate() {
        long timestamp = System.currentTimeMillis(); // 获取当前时间戳
        Date date = new Date(timestamp); // 将时间戳转换为Date对象
        return sdf.format(date);
    }

    public static String LogDate() {
        return RoomConfig.OutFilePath + Utils.getFormattedDate() + "\\";
    }

    public static final String SimpleDateFormat = "yyyy-MM-dd HH:mm:ss";
    public static final String SimpleDateFormatT = "yyyy-MM-dd HH:mm:ss.SSS";

    public static String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat(SimpleDateFormat);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }

    public static String getTimeT() {
        SimpleDateFormat formatter = new SimpleDateFormat(SimpleDateFormatT);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }

    public static void loadImageHead(String savePath, String imageUrl) {

        String imageName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);

        new Thread(() -> {

            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                InputStream inputStream = connection.getInputStream();
                String imageHeadFilePath = savePath + imageName;
                OutputStream outputStream = Files.newOutputStream(Paths.get(imageHeadFilePath));
                System.out.println("地址:" + imageHeadFilePath);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
                connection.disconnect();

                System.out.println("Image downloaded successfully.");
            } catch (Exception e) {
                String error = "loadImageHead" + e + "\n" + Arrays.toString(e.getStackTrace());
                FileUtils.writeTxtToFile(error, LogDate(), LOG_NAME_ERROR);
            }

        }).start();
    }

    public static String getImageHeadFilePath(String path, String fileName) {

        File folder = new File(path); // 指定搜索的目录路径
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.getName().equals(fileName)) {

                    //  System.out.println("找到文件: " + file.getAbsolutePath());
                    return file.getAbsolutePath(); // 如果找到文件，则返回
                }
            }
        }
        // System.out.println("未找到文件: " + fileName);
        return "";
    }

    public static String convertToBase64(String imagePath) throws IOException {
        InputStream imageInputStream = new FileInputStream(imagePath);
        byte[] imageBytes = new byte[imageInputStream.available()];
        imageInputStream.read(imageBytes);
        imageInputStream.close();

        return Base64.encodeBase64String(imageBytes);
    }

    public static long getDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String yearStr = (year + "").substring(2);
        String monthStr = month < 10 ? "0" + month : "" + month;
        String dayStr = day < 10 ? "0" + day : "" + day;
        String date = yearStr + monthStr + dayStr;

        return Long.parseLong(date) * 1000 * 1000;

    }

    public static int random(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    public static String getDateTableId() {
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);

    }

    public static String getTodayStart() {
        final String SimpleDateFormat = "yyyy-MM-dd 00:00:00";
        SimpleDateFormat formatter = new SimpleDateFormat(SimpleDateFormat);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }

    public static String getTodayEnd() {
        final String SimpleDateFormat = "yyyy-MM-dd 23:59:59";
        SimpleDateFormat formatter = new SimpleDateFormat(SimpleDateFormat);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        return formatter.format(curDate);
    }

    public static long checkingLuckyValue(long uid, long luckyValue, String sign) {
        String code = String.format("UID=%s@LUCKY_VALUE=%s@KEY=%s", uid, luckyValue, RoomConfig.LUCKY_KEY);
        String codeLog = String.format("ERROR:UID=%s@LUCKY_VALUE=%s", uid, luckyValue);
        String signCurrent = Utils.encryptMD5(code);//MD5加密
        if (!sign.equals(signCurrent)) {//记录异常修改数据
            LogWindows.getLogWindows().printToTextArea(codeLog, Utils.class);
        }
        return sign.equals(signCurrent) ? luckyValue : -1;
    }


    public static boolean checkingDailyTask(long uid, String json, String sign) {
        String code = String.format("UID=%s@JSON=%s@KEY=%s", uid, json, RoomConfig.LUCKY_KEY);
        String codeLog = String.format("ERROR:UID=%s@JSON=%s", uid, json);
        String signCurrent = Utils.encryptMD5(code);//MD5加密
        if (!sign.equals(signCurrent)) {//记录异常修改数据
            LogWindows.getLogWindows().printToTextArea(codeLog, Utils.class);
        }
        return sign.equals(signCurrent);
    }
    public static String decimalToHex(int decimal) {
        return Integer.toHexString(decimal).toUpperCase();
    }
}